package com.guxiuwei.sys.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guxiuwei.sys.common.Result;
import com.guxiuwei.sys.entity.Aporder;
import com.guxiuwei.sys.entity.Leaves;
import com.guxiuwei.sys.entity.User;
import com.guxiuwei.sys.entity.Worder;
import com.guxiuwei.sys.mapper.AporderMapper;
import com.guxiuwei.sys.mapper.WorderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 谷秀伟
 * @since 2023-03-07
 */
@RestController
@RequestMapping("/sys/aporder")
public class AporderController {

    @Autowired
    private AporderMapper aporderMapper;

    @Autowired
    private WorderMapper worderMapper;

    //获取前端传入的默认显示页码，页面容量数，
    // 和搜索框查询条件，对数据库中随工记录信息表进行分页查询
    @GetMapping("/selectAll")
    public Result<?> findPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "") String search ){
        QueryWrapper<Aporder> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("aid");
        if (StrUtil.isNotBlank(search)){
            wrapper.like("aid",search);
        }
        Page<Aporder> aporderPage = aporderMapper.selectPage(new Page<>(pageNum, pageSize),wrapper );
        System.out.println(aporderPage);
        return Result.success(aporderPage);
    }

    //权限（现场组） 签收随工，创建当前用户随工单
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('现场组')")
    public Result<?> save(@RequestBody Aporder aporder) throws ParseException {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date starttime = sdf.parse(sdf.format(d));
        aporder.setStarttime(starttime);
        aporderMapper.insert(aporder);
        return Result.success();

    }

    //权限（现场组） 在我的随工中修改随工记录
    @PutMapping("/update")
    @PreAuthorize("hasAuthority('现场组')")
    public Result<?> update(@RequestBody Aporder aporder){
        aporderMapper.updateById(aporder);
        return Result.success();
    }

     //权限（现场组） 对前端传入的aporder对象的aid进行相关记录删除操作
    @DeleteMapping("/delete/{aid}")
    @PreAuthorize("hasAuthority('现场组')")
    public Result<?> delete(@PathVariable Long aid){
        aporderMapper.deleteById(aid);
        return Result.success();
    }

    //权限（现场组） 在我的随工中展示当前用户的随工
    @GetMapping("/selectByPhone")
    public Result<?> selectByPhone(@RequestParam String phone){

        QueryWrapper<Aporder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone)
                    .eq("status","随工中");
        List<Aporder> aporders = aporderMapper.selectList(queryWrapper);
        return Result.success(aporders);
    }

    //上传接口
    @PostMapping("fileUpload")
    public Result<?> fileUpload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename(); //获取源文件名称
        String flag = IdUtil.fastSimpleUUID();
        String filePath = System.getProperty("user.dir") + "/src/main/resources/static/aporderImg/" + flag + "_" + filename; //获取上传的路径
        FileUtil.writeBytes(file.getBytes(),filePath);//把文件写入到上传路径
        return Result.success("http://localhost:8080/api/sys/aporder/getFiles/" + flag);//返回结果
    }

    //下载接口

    @GetMapping("/getFiles/{flag}")
    public void getFiles(HttpServletResponse response,@PathVariable String flag){
        OutputStream os; //输出流对象
        String filePath = System.getProperty("user.dir") + "/src/main/resources/static/aporderImg/"; //定义文件上传的根路径
        List<String> listFileNames = FileUtil.listFileNames(filePath); //获取所有文件名称
        String fileName = listFileNames.stream().filter(name -> name.contains(flag)).findAny().orElse(""); //找到和参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)){
                response.reset();
                response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(filePath + fileName);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }

    }


}

